package com.android.hidephotosplus;

import java.util.ArrayList;
import java.util.Random;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.android.hidephotosplus.adapter.MediaAdapter;
import com.android.hidephotosplus.db.DbHelper;
import com.android.hidephotosplus.db.DbProvider;
import com.android.hidephotosplus.interfaces.MInterface.onTask;
import com.android.hidephotosplus.model.ModelAlbum;
import com.android.hidephotosplus.model.ModelMedia;
import com.android.hidephotosplus.util.Camera;
import com.android.hidephotosplus.util.Config;
import com.android.hidephotosplus.util.PasswordManager;
import com.android.hidephotosplus.util.Util;
import com.android.hidephotosplus.util.Util.HiddenMedia;

public class ActivityAlbumView extends SherlockActivity implements
		OnScrollListener, OnItemLongClickListener, OnItemClickListener {

	private GridView mGridView;

	private MediaAdapter mMediaAdapter;

	private ArrayList<ModelMedia> arrMedias;

	private long idAlbum = 0;

	private String nameAlbum = null;

	private ActionBar mActionBar;

	private ActionMode mActionMode;

	private boolean isStartActionMode = false;

	private boolean isCheckAll = false;

	private boolean isPublic;

	private ArrayList<ModelMedia> arrMediasSelected = new ArrayList<ModelMedia>();

	private DbHelper mDbHelper;

	private DbProvider mDbProvider;

	private Reciever mReciever;

	private String navigationSelected = null;

	private String pathAlbum = null;

	private ModelAlbum mAlbum = new ModelAlbum();

	private Camera camera = null;

	private static boolean IS_START_PASSWORD = false;

	private PasswordManager mPasswordManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_media_view);

		mActionBar = getSupportActionBar();
		mActionBar.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.bg_actionbar));

		mDbHelper = DbHelper.getInstance(getApplicationContext());
		mDbProvider = DbProvider.getinstance(getApplicationContext());

		mPasswordManager = new PasswordManager(this);
		mGridView = (GridView) findViewById(R.id.gridMedia);

		IS_START_PASSWORD = false;

		Intent intent = getIntent();
		if (intent.getExtras() != null
				&& intent.hasExtra(Config.KEY_ALBUM_STOCK)) {
			mAlbum = intent.getExtras().getParcelable(Config.KEY_ALBUM_STOCK);
			if (mAlbum != null) {
				idAlbum = mAlbum.getIdAlbum();
				nameAlbum = mAlbum.getNameAlbum();
				navigationSelected = intent.getExtras().getString(
						Config.KEY_NAVIGATION_SELECTED);
				if (navigationSelected != null) {
					if (navigationSelected
							.equals(getString(R.string.all_media))) {
						arrMedias = mDbProvider.getAllMedias(idAlbum);
					} else if (navigationSelected
							.equals(getString(R.string.photos))) {
						arrMedias = mDbProvider.getAllPhotos(idAlbum);
					} else {
						arrMedias = mDbProvider.getAllVideos(idAlbum);
					}
				} else
					arrMedias = mDbProvider.getAllMedias(idAlbum);
				mMediaAdapter = new MediaAdapter(getApplicationContext(),
						arrMedias, true);
				isPublic = true;
			}
		} else if (intent.getExtras() != null
				&& intent.hasExtra(Config.KEY_ALBUM_HIDDEN)) {
			mAlbum = intent.getExtras().getParcelable(Config.KEY_ALBUM_HIDDEN);
			if (mAlbum != null) {
				idAlbum = mAlbum.getIdAlbum();
				nameAlbum = mAlbum.getNameAlbum();
				pathAlbum = mAlbum.getPathAlbum();
				navigationSelected = intent.getExtras().getString(
						Config.KEY_NAVIGATION_SELECTED);

				if (navigationSelected != null) {
					if (navigationSelected
							.equals(getString(R.string.all_media))) {
						arrMedias = mDbHelper.getAllMedia(idAlbum);
					} else if (navigationSelected
							.equals(getString(R.string.photos))) {
						arrMedias = mDbHelper.getAllPhotos(idAlbum);
					} else {
						arrMedias = mDbHelper.getAllVideos(idAlbum);
					}
				}
				mMediaAdapter = new MediaAdapter(getApplicationContext(),
						arrMedias, false);
				isPublic = false;
			}
		}

		if (nameAlbum != null)
			mActionBar.setTitle(nameAlbum);

		if (mMediaAdapter != null)
			mGridView.setAdapter(mMediaAdapter);

		mGridView.setOnScrollListener(this);
		mGridView.setOnItemLongClickListener(this);
		mGridView.setOnItemClickListener(this);

		registerBroadcast();

	}

	@Override
	protected void onPause() {
		super.onPause();
		IS_START_PASSWORD = true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (IS_START_PASSWORD) {
			mPasswordManager.checkSetupOrUnlockPass();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		if (isPublic)
			inflater.inflate(R.menu.menu_album_view_stock, menu);
		else
			inflater.inflate(R.menu.menu_album_view_hidden, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add_media:
			Intent intentAddMedia = new Intent(this,
					ActivityGalleryForResult.class);
			intentAddMedia.putExtra(Config.KEY_NAME_ALBUM_HIDDEN, nameAlbum);
			intentAddMedia.putExtra(Config.KEY_ID_ALBUM_HIDDEN, idAlbum);
			startActivityForResult(intentAddMedia,
					Config.REQUEST_CODE_START_ACTIVITY_GALLERY);
			break;
		case R.id.menu_slide:
			Intent intent = new Intent(this, ActivityViewMedia.class);
			intent.putParcelableArrayListExtra(Config.KEY_ARR_MEDIA, arrMedias);
			intent.putExtra(Config.KEY_IS_PUBLIC, isPublic);
			intent.putExtra(Config.KEY_POSITION_ARR_MEDIA, 0);
			intent.putExtra(Config.KEY_SLIDE_SHOW, true);
			startActivity(intent);
			break;
		case R.id.menu_camera:
			camera = Camera.getInstance(this);
			camera.startCamera(pathAlbum);
			break;
		case R.id.menu_record:
			camera = Camera.getInstance(this);
			camera.startRecord(pathAlbum);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (view.getId() == R.id.gridMedia) {
			if (scrollState == SCROLL_STATE_FLING) {
				mMediaAdapter.setScroolState(true);
			} else {
				mMediaAdapter.setScroolState(false);
				mMediaAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int position, long arg3) {
		if (!isStartActionMode) {
			mActionMode = startActionMode(new AnActionMode(isPublic));
		}
		setSelectedUnSelected(position);
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (isStartActionMode)
			setSelectedUnSelected(position);
		else {
			Intent intent = new Intent(this, ActivityViewMedia.class);
			intent.putParcelableArrayListExtra(Config.KEY_ARR_MEDIA, arrMedias);
			intent.putExtra(Config.KEY_IS_PUBLIC, isPublic);
			intent.putExtra(Config.KEY_POSITION_ARR_MEDIA, position);
			intent.putExtra(Config.KEY_NAVIGATION_SELECTED, navigationSelected);
			startActivityForResult(intent, Config.REQUEST_CODE_START_ACTIVITY);
		}
	}

	private class AnActionMode implements ActionMode.Callback {
		private boolean isPublic;

		public AnActionMode(boolean isPublic) {
			this.isPublic = isPublic;
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			MenuInflater inflater = getSupportMenuInflater();
			if (isPublic)
				inflater.inflate(R.menu.actionmode_album_view_stock, menu);
			else
				inflater.inflate(R.menu.actionmode_album_view_hidden, menu);
			isStartActionMode = true;
			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			switch (item.getItemId()) {
			case R.id.menu_check_all:
				if (!isCheckAll) {
					setCheckUncheckAll(true);
					isCheckAll = true;
				} else {
					setCheckUncheckAll(false);
					isCheckAll = false;
				}
				break;
			case R.id.menu_hide:
				new HiddenMedia(ActivityAlbumView.this, arrMediasSelected,
						null, null, true, new onTask() {
							@Override
							public void onTaskComplete(Object object) {
								ActivityAlbumView.this.arrMedias
										.removeAll(arrMediasSelected);
								mMediaAdapter.notifyDataSetChanged();
								arrMediasSelected.clear();
								mActionMode.finish();
								sendBoardcastNameAlbumHidden(nameAlbum);
							}
						}).execute();
				break;
			case R.id.menu_unhide:
				new Util.UnHideMedia(ActivityAlbumView.this, arrMediasSelected,
						null, null, true, new onTask() {
							@Override
							public void onTaskComplete(Object object) {
								ActivityAlbumView.this.arrMedias
										.removeAll(arrMediasSelected);
								mMediaAdapter.notifyDataSetChanged();
								arrMediasSelected.clear();
								mActionMode.finish();
								sendBoardcastNameAlbumStock(nameAlbum);
							}
						}).execute();
				break;
			case R.id.menu_delete:
				if (isPublic) {
					new Util.DeleteMediaStock(ActivityAlbumView.this,
							arrMediasSelected, null, navigationSelected, true,
							new onTask() {
								@Override
								public void onTaskComplete(Object object) {
									ActivityAlbumView.this.arrMedias
											.removeAll(arrMediasSelected);
									mMediaAdapter.notifyDataSetChanged();
									arrMediasSelected.clear();
									mActionMode.finish();
									sendBoardcastNameAlbumStock(nameAlbum);
								}
							}).execute();
					break;
				} else {
					new Util.DeleteMediaHidden(ActivityAlbumView.this,
							arrMediasSelected, null, navigationSelected, true,
							new onTask() {
								@Override
								public void onTaskComplete(Object object) {
									ActivityAlbumView.this.arrMedias
											.removeAll(arrMediasSelected);
									mMediaAdapter.notifyDataSetChanged();
									arrMediasSelected.clear();
									mActionMode.finish();
									sendBoardcastNameAlbumStock(nameAlbum);
								}
							}).execute();
					break;
				}

			case R.id.menu_share:
				if (isPublic)
					new Util.ShareFileStock(ActivityAlbumView.this, null,
							arrMediasSelected, navigationSelected).execute();
				else
					new Util.ShareFileHidden(ActivityAlbumView.this, null,
							arrMediasSelected, navigationSelected).execute();
				break;
			default:
				break;
			}

			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			isStartActionMode = false;
			setCheckUncheckAll(false);
			arrMediasSelected.clear();
		}

	}

	public void setSelectedUnSelected(int position) {
		arrMedias.get(position).isChecked = !arrMedias.get(position).isChecked;
		mMediaAdapter.notifyDataSetChanged();
		if (arrMedias.get(position).isChecked)
			arrMediasSelected.add(arrMedias.get(position));
		else
			arrMediasSelected.remove(arrMedias.get(position));
		mActionMode.setTitle(arrMediasSelected.size() + " "
				+ getString(R.string.selected));
		mMediaAdapter.notifyDataSetChanged();
	}

	private void setCheckUncheckAll(boolean isChecked) {
		if (arrMediasSelected.size() > 0)
			arrMediasSelected.clear();

		for (ModelMedia item : arrMedias) {
			if (isChecked) {
				item.setChecked(true);
				arrMediasSelected.add(item);
			} else {
				arrMediasSelected.clear();
				item.setChecked(false);
			}
		}
		setTitleActionMode();
		mMediaAdapter.notifyDataSetChanged();
	}

	private void setTitleActionMode() {
		mActionMode.setTitle(arrMediasSelected.size() + " "
				+ getString(R.string.selected));
	}

	private void sendBoardcastNameAlbumHidden(String nameAlbum) {
		Intent intent = new Intent();
		intent.setAction(Config.ACTION_SEND_NAME_ALBUM_TO_HIDDEN);
		intent.putExtra(Config.KEY_NAME_ALBUM_HIDDEN, nameAlbum);
		sendBroadcast(intent);
	}

	private void sendBoardcastNameAlbumStock(String nameAlbum) {
		Intent intent = new Intent();
		intent.setAction(Config.ACTION_SEND_NAME_ALBUM_TO_STOCK);
		intent.putExtra(Config.KEY_NAME_ALBUM_STOCK, nameAlbum);
		sendBroadcast(intent);
	}

	private void registerBroadcast() {
		try {
			IntentFilter filter = new IntentFilter();
			filter.addAction(Config.ACTION_SEND_POSITON_HIDE_DELETE);
			mReciever = new Reciever();
			registerReceiver(mReciever, filter);
		} catch (Exception e) {
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			unregisterReceiver(mReciever);
		} catch (Exception e) {
		}
	}

	private class Reciever extends BroadcastReceiver {
		@Override
		public void onReceive(Context arg0, Intent intent) {
			Log.e("receiver", "receiver");
			if (intent.getAction().equals(
					Config.ACTION_SEND_POSITON_HIDE_DELETE)) {
				int position = intent.getExtras().getInt(
						Config.KEY_SEND_POSITON_HIDE_DELETE);
				if (position != -1) {
					arrMedias.remove(position);
					mMediaAdapter.notifyDataSetChanged();
				} else {
					Log.e("arr null size", "null");
				}
			}

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("requestCode view", requestCode + "");
		switch (requestCode) {
		case Config.REQUEST_CODE_START_ACTIVITY_GALLERY:
			IS_START_PASSWORD = false;
			if (resultCode == RESULT_OK) {
				ArrayList<ModelMedia> arrMedias = data
						.getParcelableArrayListExtra(Config.KEY_REQUEST_ARR_MEDIA_TO_HIDE);
				if (arrMedias != null && arrMedias.size() > 0) {
					for (ModelMedia modelMedia : arrMedias) {
						this.arrMedias
								.add(0, mDbHelper.getMediaById(modelMedia
										.getIdMedia()));
					}
					mMediaAdapter.notifyDataSetChanged();
				}
			}
			break;
		case Config.REQUEST_CODE_CAPTURE_IMAGE:
			IS_START_PASSWORD = false;
			if (resultCode == RESULT_OK) {
				if (camera != null) {
					resultCamera(Config.TYPE_PHOTO);
				}
			}
			break;
		case Config.REQUEST_CODE_CAPTURE_VIDEO:
			IS_START_PASSWORD = false;
			if (resultCode == RESULT_OK) {
				if (camera != null) {
					resultCamera(Config.TYPE_VIDEO);
				}
			}
			break;
		case Config.REQUEST_CODE_START_PATTERN_PASSWORD:
			if (resultCode == Activity.RESULT_OK) {
				IS_START_PASSWORD = false;
			}
			break;
		case Config.REQUEST_CODE_START_ACTIVITY:
			IS_START_PASSWORD = false;
			break;
		case Config.REQUEST_CODE_SHARE_FILE:
			IS_START_PASSWORD = false;
			mActionMode.finish();
			break;
		default:
			break;
		}
	}

	private void resultCamera(int type) {
		String stockPath = camera.pathCamera() + camera.getNamePhoto();
		String hiddenPath = camera.getCurrentFile().getAbsolutePath();
		String namePhoto = camera.getNamePhoto();
		long idMedia = new Random().nextLong();
		ModelMedia media = new ModelMedia();
		media.setPathMediaHidden(hiddenPath);
		media.setPathMediaStock(stockPath);
		media.setIdMedia(idMedia);
		media.setIdAlbum(idAlbum);
		media.setDate(String.valueOf(System.currentTimeMillis()));
		media.setNameMedia(namePhoto);
		if (type == Config.TYPE_PHOTO) {
			media.setTypeMedia(Config.TYPE_PHOTO);
			media.setVideo(false);
		} else {
			media.setTypeMedia(Config.TYPE_VIDEO);
			media.setVideo(true);
		}
		arrMedias.add(0, media);
		mMediaAdapter.notifyDataSetChanged();
		mDbHelper.insertMedia(media);
	}
}
